<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
      <div>
        <n-form ref="form"
                :model="searchCondition"
                :show-require-mark="false"
                label-align="right"
                label-placement="left"
                label-width="80px">
          <div>
            <div class="grid md:flex md:flex-wrap md:gap-x-1">
              <n-form-item>
                <label style="width: 100px">仓库货物名称：</label>
                <n-input style="width: 150px;" v-model:value="searchCondition.productName" clearable/>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <label>仓库：</label>
                <n-select
                  v-model:value="searchCondition.storeId"
                  :options="stores"
                  />
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <label>预警状态：</label>
                <n-select v-model:value="searchCondition.status"
                          :options="statusOptions"></n-select>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <n-button @click="searchByCondition"
                          type="primary">筛选</n-button>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <n-button @click="showForm=true"
                          type="primary">添加库存</n-button>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <n-button @click="deleteSelectInventory"
                          type="error">批量删除</n-button>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <n-button @click="exportListInfo"
                          type="primary">导出</n-button>
              </n-form-item>
            </div>
          </div>
        </n-form>
        <AddInventoryForm :show="showForm" @update-page="searchByCondition" :onClose="handleClose"/>
        <UpdateInventory
            @update-page="searchByCondition"
            :show1="showForm1"
            :onClose="handleClose"
            :inventory="currentInventory"
        />
      <n-data-table
          remote
          :single-line="false"
          ref="table"
          :columns="columns"
          :data="inventoryList"
          :loading="loading"
          :pagination="paginationReactive"
          :row-key="rowKey"
          :scroll-x="900"
          @update:checked-row-keys="handleCheck"
      />
      </div>
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
  import {h, onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate, formatDateTime} from "@/utils";
import {NTag} from 'naive-ui'
import StoreActions from "@/views/admin/category/components/category-actions.vue"
import AddInventoryForm from './components/inventory-add.vue'
import UpdateInventory from './components/inventory-edit.vue'

const searchCondition=ref({
  storeId:-1,
  productName:'',
  status:'全部',
})
const stores=ref([])
stores.value.push(
  {
      label:'全部',
      value:-1,
  }
)
const exportListInfo = async () => {
  const res = await api.exportInventoryList({
    productName:searchCondition.value.productName,
    storeId:searchCondition.value.storeId,
    status:searchCondition.value.status,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const queryStoreList = async () => {
loading.value = true
try {
  const res = await api.findAllStore()
  if(res.code === 200) {
    res.data.map((item)=>{
      stores.value.push({
        label: item.name,
        value: item.id
      })
    })
  }
  else {
    $message.error(res.message)
  }
} catch (err) {
  $message.error("获取仓库信息失败！")
}finally{
  loading.value = false
}
}
const statusOptions=ref([
  {
    label: '全部',
    value: '全部',
  },
  {
    label:'是',
    value:'insufficient',
  },
  {
    label: '否',
    value: 'enough',
  }
])
function handleChange(value) {
  console.log(value)
}
const showForm = ref(false);
const showForm1 = ref(false);
const handleClose = () => {
  showForm.value = false;
  showForm1.value=false;
};
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const inventoryList = ref([])
const checkedRowKeysRef = ref([]);
const handleCheck =(rowKeys)=>{
  checkedRowKeysRef.value = rowKeys;
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
  {
    key: 'productName',
    title: '仓库货物名称',
    width: 300,
  },
  {
    key: 'storeName',
    title: '仓库',
    width: 100,

  },
  {
    key: 'quantity',
    title: '可用量',
    width: 80,

  },
  {
    key: 'minimumQuantity',
    title: '期望可用量',
    width: 80,

  },
  {
    key: 'status',
    title: '预警状态',
    width:100,
    render(row) {
	    if(row.status === "正常") {
				return h(
            NTag,
            {
              type: 'success',
              bordered: false
            },
            {
              default: () => '正常'
            }
        );
      }
			else if(row.status === "异常") {
				return  h(
            NTag,
            {
              type: 'error',
              bordered: false
            },
            {
              default: () => '异常'
            }
        );
      }
    }
  },
  {
    key: 'operation',
    title: '操作',
    width: 100,
    render(row) {
      return h(
       StoreActions,
        {
          onClickDelete: () => onDeleteInventory(row),
          onClickEdit: () => onDetailInventory(row),
        }
      );
    }
  },
]
let total = 0
const paginationReactive = reactive({
  page: 1,
  pageSize: 50,
  showSizePicker: true,
  pageSizes: [50, 100, 150],
  itemCount:0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});

const deleteSelectInventory = ()=>{
  if(checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择仓库货物信息！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选仓库货物信息？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      console.log(ids)
      loading.value = true
      try {
        const res = await api.deleteInventories({params:{ids}})
        if(res.code === 200) {
          $message.success("删除所选仓库货物信息成功！")
          // await queryByPage()
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选仓库货物失败！")
      }finally{
        loading.value = false
      }
    },
  })
}
const searchByCondition = async ()=>{
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageInventory({
      params: {
	      ...searchCondition.value,
	      pageNum:paginationReactive.page,
	      pageSize:paginationReactive.pageSize,
      }
    })
    if(res.code === 200) {
	    total = res.data.total
	    paginationReactive.itemCount = total
	    const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
	    inventoryList.value = res.data.records.map((item,i)=>{
		    return {...item,
			    colId: baseCount + i + 1,
		    }
	    })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询仓库货物失败！")
  }finally{
    loading.value = false
  }
}
const onDeleteInventory = async (log)=>{
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前仓库货物？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = log
      loading.value = true
      try {
        const res = await api.deleteInventory({id})
        if(res.code === 200) {
          $message.success("删除仓库货物成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除仓库货物失败！")
      }finally{
        loading.value = false
      }
    }
  })
}
const currentInventory = ref(null);
const onDetailInventory = async (inventory)=>{
  const {id} = inventory
  showForm1.value=true;
  currentInventory.value = inventory;
}
const queryByPage = async ()=>{
  loading.value = true
  try {
    const res = await api.findPageInventory(
        {
          params: {
	          pageNum:paginationReactive.page,
	          pageSize:paginationReactive.pageSize,
          }
        })
    if(res.code === 200) {
	    total = res.data.total
	    paginationReactive.itemCount = total
	    const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
	    inventoryList.value = res.data.records.map((item,i)=>{
		    return {...item,
			    colId: baseCount + i + 1,
		    }
	    })
      $message.success("获取仓库货物成功！")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库货物失败！")
  }finally{
    loading.value = false
  }
}
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(()=>{
	queryStoreList()
  queryByPage()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
  text-align: center;

}
:deep(.n-select) {
  width: 140px !important;
}

:deep(.two-line-description) {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 控制显示的行数 */
  overflow: hidden;
}

</style>
